package xhhx.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;
import xhhx.manager.ActorManager;
import xhhx.network.C2sMsg;

public class ServerHandler extends SimpleChannelInboundHandler<C2sMsg> {
    @Override
    public void channelRead0(ChannelHandlerContext ctx, C2sMsg msg) throws Exception {
        try {
            ActorManager.DealWith(ctx.channel(), msg);
        } finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        ActorManager.AddLink(ctx.channel());

        System.out.println("In IP:" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

        ActorManager.RemoveLink(ctx.channel());
        System.out.println("Out IP:" + ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
